// 引入必要的库和模块
import { defineConfig, loadEnv, ConfigEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// 定义一个接口来表示代理配置的选项
interface ProxyOptions {
  target: string
  changeOrigin: boolean
  rewrite: (path: string) => string
}

// 导出 Vite 配置
export default defineConfig((config: ConfigEnv) => {
  // 加载当前环境的配置变量
  const env = loadEnv(config.mode, process.cwd())

  // 动态生成代理配置
  const generateProxyConfig = () => {
    const config: Record<string, ProxyOptions> = {}

    // 用户服务代理配置
    config['/api/user'] = {
      target: env.VITE_API_USER_SERVICE,
      changeOrigin: true,
      rewrite: (path: string) => {
        const rewrittenPath = path.replace(/^\/api\/user/, '')
        console.log(`Rewriting user path: ${path} -> ${rewrittenPath}`)
        return rewrittenPath
      },
    }

    // 认证服务代理配置
    config['/api/hbteck-auth'] = {
      target: env.VITE_API_AUTH_SERVICE,
      changeOrigin: true,
      rewrite: (path: string) => {
        const rewrittenPath = path.replace(/^\/api\/hbteck-auth/, '')
        console.log(`Rewriting auth path: ${path} -> ${rewrittenPath}`)
        return rewrittenPath
      },
    }

    // 默认服务代理配置
    config['/api'] = {
      target: env.VITE_API_DEFAULT_SERVICE,
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/api/, ''),
    }

    return config
  }

  return {
    // 设置项目的基础路径
    base: './',

    // 插件配置，使用 Vue 插件
    plugins: [vue()],

    // 配置路径别名
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },

    // 开发服务器配置
    server: {
      proxy: env.VITE_API_GATEWAY ? {} : generateProxyConfig(),
    },

    // CSS 配置
    css: {
      preprocessorOptions: {
        css: {
          // 自动导入全局样式文件
          additionalData: `@import "@/assets/styles/main.css";`,
        },
      },
    },
  }
})
